package com.sh.ssao.lottery.config.utils;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {
    String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";

    /**
     * 发送HttpPost请求，参数为json字符串 * * @param url * @param jsonStr * @return
     */
    public String sendPost(String url, String jsonStr, int requestTimeout, int socketTimeout, int connectTimeout) throws ConnectTimeoutException, SocketTimeoutException, IOException, Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        if (requestTimeout == 0)
            requestTimeout = 3000;
        if (socketTimeout == 0)
            socketTimeout= 3000;
        if (connectTimeout == 0)
            connectTimeout = 3000;

        String result = null;
        // 字符串编码
        StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
        // 设置content-type
        entity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
        //设置请求查实3秒
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(requestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);
        //设置不使用长连接
        httpPost.setHeader("Connection", "close");
        // 接收参数设置
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity, "utf-8");
        } catch (ConnectTimeoutException ex) {
            throw ex;
        } catch (SocketTimeoutException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭CloseableHttpResponse
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * get1
     * @param url
     * @return
     */
    public List<Map<String,Object>> sendGet(String url) {
        try {
            // 1.拿到一个httpclient的对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 2.设置请求方式和请求信息
            HttpGet httpGet = new HttpGet(url);
            // 3.执行请求
            CloseableHttpResponse response = null;
            response = httpClient.execute(httpGet);
            // 4.获取返回值
            String returnval = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
            // 5.打印
            List<Map<String,Object>> lm = new HttpClientUtils().stringHandle(returnval);
            return lm;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * get获取数据
     * @param url
     * @return
     * @throws IOException
     */
    public List<Map<String,Object>> doGet(String url) throws IOException {
        List<Map<String,Object>> lm = null;
        HttpClientUtils hc = new HttpClientUtils();
        //指定请求方式
        HttpGet httpGet = new HttpGet(url);
        //获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //执行发送请求并响应结果
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            //请求成功，返回数据
            HttpEntity entity = httpResponse.getEntity();
            //将请求中的响应结果换成字符并加上字符集设置
            String str = EntityUtils.toString(entity,"utf-8");
            lm = hc.stringHandle(str);
        }
        return lm;
    }

    /**
     * 字符串处理
     * @return
     */
    public List<Map<String,Object>> stringHandle(String val){
        System.out.println(val);
        List<Map<String,Object>> lm = new ArrayList<>();
        String[] ls = val.split(";");
        for (String v:ls) {
            Map<String,Object> map = new HashMap<>();
            String s = v.replaceAll("(var hq_str_)|(\")|(,\")","");
            String[] chs =  s.split("=");

            if(chs.length>=2){
                map.put("shares_code",chs[0].trim());//股票代码
                String codes = chs[1];
                System.out.println(codes);
                String[] cs = codes.split(",");
                if (cs.length>3){
                    map.put("shares_now_price",cs[3]);//当前价格
                }
                lm.add(map);
            }else {
                System.out.println("数据错误："+v);
            }
        }
        return lm;
    }
    /**
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {

        HttpClientUtils hcu = new HttpClientUtils();
        /*Map<String,String> paramasMap = new HashMap<>();
        paramasMap.put("list","sh000001,sh000002,sh000003,sz399001,sz399002,sz399003,sz399005,sz399006,sh000300,sh000016,sh000011,sh600000,sh601211,sh600018");
        String s = hcu.sendPost("http://hq.sinajs.cn/","",0,0,0);
        System.out.println(s);*/

//        List<Map<String,Object>> lm = hcu.sendGet("http://hq.sinajs.cn/list=sh000001,sh000002,sh000003,sz399001,sz399002,sz399003,sz399005,sz399006,sh000300,sh000016,sh000011,sh600000,sh601211,sh600018");
//        System.out.println(lm);

        String code = "SH601211,SH600018,SH601601,SH601601,SH600000,SH601601,SH601618,SZ300358,SH601318,SH600716,SZ002589,SH600869,SZ002583,SH600312,SH601618,SH600547,SH600708,SZ002589,SH600637,SH600056,SZ300358,SZ002034,SH600572,SH600129,SZ002479,SH600398,SH600029,SH110059,SZ002240,SH600150,SH000948,SH688180,SZ300433,SH603068";
        hcu.doGet("http://hq.sinajs.cn/list="+code);

    }
}
